import React from 'react';
import { Row, Col, Form, Icon, Input, Button, Checkbox, message } from 'antd';
import { FormProps } from 'antd/lib/form';
import axios from 'axios';
import { useHistory } from 'react-router-dom';

const NormalLoginForm = (props: FormProps) => {
  let history = useHistory();

  const handleSubmit = (e: any) => {
    e.preventDefault();
    if (props.form !== undefined) {
      props.form.validateFields((err: any, values: any) => {
        if (!err) {
          axios
            .post('/login', values)
            .then(() => {
              message.success('登录成功！');
              history.replace('/devices');
            })
            .catch((error) => {
              if (error.response?.status === 401) {
                message.error('用户名或者密码错误！');
              }
            });
        }
      });
    }
  };

  if (props.form !== undefined) {
    const { getFieldDecorator } = props.form;
    return (
      <Form onSubmit={handleSubmit}>
        <Form.Item>
          {getFieldDecorator('user', {
            rules: [{ required: true, message: '请输入用户名' }]
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="用户名"
            />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码' }]
          })(
            <Input.Password
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="密码"
            />
          )}
        </Form.Item>
        <Form.Item>
          <Row>
            <Col span={12}>
              {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true
              })(<Checkbox>记住我</Checkbox>)}
            </Col>
            <Col span={12}>
              <Button type="primary" htmlType="submit" style={{ width: '50%', float: 'right' }}>
                登录
              </Button>
            </Col>
          </Row>
        </Form.Item>
      </Form>
    );
  }
  return <div>error</div>;
};

const LoginForm = Form.create({ name: 'normal_login' })(NormalLoginForm);

const Login = () => {
  return (
    <Row>
      <Col span={8} offset={8}>
        <LoginForm />
      </Col>
    </Row>
  );
};

export default Login;
